package cn.waka.sys.admin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import cn.waka.sys.admin.object.Page;
import cn.waka.sys.admin.object.Result;
import cn.waka.sys.admin.object.Role;
import cn.waka.sys.admin.object.User;
import cn.waka.sys.admin.service.RoleService;
import cn.waka.sys.admin.service.UserService;
import cn.waka.sys.admin.utils.Validator;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @GetMapping(path = "/index", name = "用户分页")
    public ModelAndView pageList(HttpServletRequest req, HttpServletResponse res) {
        String pStr = req.getParameter("page");
        Page p = new Page();
        if (pStr != null && Validator.isNum(pStr)) {
            p.setPage(Integer.parseInt(pStr));
        }
        String sizeStr = req.getParameter("size");
        if (sizeStr != null && Validator.isNum(sizeStr)) {
            p.setSize(Integer.parseInt(sizeStr));
        }

        String login = req.getParameter("login");
        String uname = req.getParameter("uname");
        Map<String, String> param = new HashMap<String, String>();
        ModelAndView mv = new ModelAndView();
        String search_param = "";
        if (login != null && login.length() > 0) {
            param.put("login", "%" + login + "%");
            mv.addObject("search_login", login);
            search_param += "&login=" + login;
        }
        if (uname != null && uname.length() > 0) {
            param.put("uname", "%" + uname + "%");
            mv.addObject("search_uname", uname);
            search_param += "&uname=" + uname;
        }

        userService.findPage(p, param);

        mv.addObject("page", p);
        mv.addObject("search_param", search_param);
        return mv;

    }

    @GetMapping(path = "/pass", name = "修改密码")
    public ModelAndView pass(HttpServletRequest req, HttpServletResponse res) {
        HttpSession sess = req.getSession();
        User u = new User();

        if (sess.getAttribute("uid") != null) {
            int id = (int) sess.getAttribute("uid");
            u.setId(id);
        }
        if (sess.getAttribute("uname") != null) {
            String uname = (String) sess.getAttribute("uname");
            u.setUsername(uname);
        }

        ModelAndView mv = new ModelAndView();

        mv.addObject("obj", u);
        return mv;

    }

    @PostMapping(path = "/savepass", name = "保存密码")
    @ResponseBody
    public Result savePass(HttpServletRequest req, HttpServletResponse res, HttpSession sess) {
        String oldPass = req.getParameter("oldpassword");
        if (oldPass == null || oldPass.length() == 0) {
            return error(0, "旧密码不能为空！");
        }

        String password = req.getParameter("password");
        String repassword = req.getParameter("repassword");

        if (password == null || repassword == null) {
            return error(0, "新密码不能为空！");
        }

        Object idObj = sess.getAttribute("uid");
        if (idObj != null) {
            int id = (int) idObj;
            User u = userService.findById(id);
            if (u == null) {
                return error(0, "用户不存在！");
            }
            oldPass = DigestUtils.md5DigestAsHex(oldPass.toString().getBytes()).toLowerCase();
            if (!oldPass.equals(u.getPassword())) {
                return error(0, "旧密码不正确！");
            }
            password = DigestUtils.md5DigestAsHex(password.toString().getBytes()).toLowerCase();
            boolean rs = userService.updatePassword(id, password);
            if (rs) {
                return error(1, "保存成功！");
            } else {
                return error(0, "保存失败！");
            }
        }
        return error(0, "login");
    }

    @RequestMapping(path = "/info", name = "查看用户信息")
    public ModelAndView info(HttpServletRequest req, HttpServletResponse res, HttpSession sess) {
        int id = (int) sess.getAttribute("uid");
        User user = userService.findById(id);
        if (user == null) {
            user = new User();
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("obj", user);
        return mv;
    }


    @RequestMapping(path = "/edit", name = "编辑用户信息")
    public ModelAndView edit(HttpServletRequest req, HttpServletResponse res) {
        String idStr = req.getParameter("uid");
        int id = 0;
        if (idStr != null && Validator.isNum(idStr)) {
            id = Integer.parseInt(idStr);
        }
        User user = userService.findById(id);
        if (user == null) {
            user = new User();
        }

        List<Role> roleList = roleService.findAll();
        if (user.getAuthorize() != null) {
            String[] authorizes = user.getAuthorize().split(",");
            for (int i = 0; i < roleList.size(); i++) {
                boolean status = false;
                for (String authorize : authorizes) {
                    if (Integer.parseInt(authorize) == roleList.get(i).getId()) {
                        status = true;
                    }
                }
                roleList.get(i).setStatus(status);
            }
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("obj", user);
        mv.addObject("roleList", roleList);
        return mv;
    }

    @RequestMapping(path = "/savec", name = "保存用户信息")
    @ResponseBody
    public Result savec(HttpServletRequest req, HttpServletResponse res, HttpSession sess) {
        int id = (int) sess.getAttribute("uid");

        String username = req.getParameter("username");
        String login = req.getParameter("login");
        String email = req.getParameter("email");

        String desc = req.getParameter("desc");
        User user = new User();
        user.setId(id);
        user.setUsername(username);
        user.setLogin(login);
        user.setEmail(email);
        user.setDesc(desc);
        int rs = userService.saveUser(user);

        if (rs > 0) {
            return error(1, "保存成功！");
        } else {
            return error(0, "保存失败！");
        }
    }

    @RequestMapping(path = "/save", name = "保存用户信息")
    @ResponseBody
    public Result save(HttpServletRequest req, HttpServletResponse res) {
        String idStr = req.getParameter("id");
        int id = 0;
        if (idStr != null && Validator.isNum(idStr)) {
            id = Integer.parseInt(idStr);
        }
        String username = req.getParameter("username");
        String login = req.getParameter("login");
        String email = req.getParameter("email");
        String[] authorize = req.getParameterValues("authorize[]");
        String desc = req.getParameter("desc");
        User user = new User();
        user.setId(id);
        user.setUsername(username);
        user.setLogin(login);
        user.setEmail(email);
        user.setAuthorize(StringUtils.arrayToCommaDelimitedString(authorize));
        user.setDesc(desc);
        int rs = userService.saveUser(user);

        if (rs > 0) {
            return error(1, "保存成功！");
        } else {
            return error(0, "保存失败！");
        }
    }


    @RequestMapping(path = "/auth", name = "显示用户权限")
    public ModelAndView auth(HttpServletRequest req, HttpServletResponse res) {
        String idStr = req.getParameter("uid");
        int id = 0;
        if (idStr != null && Validator.isNum(idStr)) {
            id = Integer.parseInt(idStr);
        }
        User user = userService.findById(id);
        if (user == null) {
            user = new User();
        }

        List<Role> roleList = roleService.findAll();
        if (user.getAuthorize() != null) {
            String[] authorizes = user.getAuthorize().split(",");
            for (int i = 0; i < roleList.size(); i++) {
                boolean status = false;
                for (String authorize : authorizes) {
                    if (Integer.parseInt(authorize) == roleList.get(i).getId()) {
                        status = true;
                    }
                }
                roleList.get(i).setStatus(status);
            }
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("obj", user);
        mv.addObject("roleList", roleList);
        return mv;
    }

    @RequestMapping(path = "/saveAuth", name = "保存用户授权")
    public Result saveAuth(HttpServletRequest req, HttpServletResponse res) {
        String idStr = req.getParameter("id");
        int id = 0;
        if (idStr != null && Validator.isNum(idStr)) {
            id = Integer.parseInt(idStr);
        }
        String[] authorize = req.getParameterValues("authorize[]");
        String auth = StringUtils.arrayToCommaDelimitedString(authorize);
        int rs = userService.saveAuth(id, auth);

        if (rs > 0) {
            return error(1, "保存成功！");
        } else {
            return error(0, "保存失败！");
        }
    }

    @RequestMapping(path = "/editPass", name = "编辑密码")
    public ModelAndView eidtPass(HttpServletRequest req, HttpServletResponse res) {
        String idStr = req.getParameter("uid");
        int id = 0;
        if (idStr != null && Validator.isNum(idStr)) {
            id = Integer.parseInt(idStr);
        }
        User user = userService.findById(id);
        if (user == null) {
            user = new User();
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("obj", user);
        return mv;

    }

    @RequestMapping(path = "/updatePass", name = "保存密码")
    @ResponseBody
    public Result updatePass(HttpServletRequest req, HttpServletResponse res) {
        String idStr = req.getParameter("uid");
        int id = 0;
        if (idStr != null && Validator.isNum(idStr)) {
            id = Integer.parseInt(idStr);
        }
        String password = req.getParameter("password");
        String repassword = req.getParameter("repassword");
        if (password == null || repassword == null) {
            return error(0, "新密码不能为空！");
        }
        if (!password.equals(repassword)) {
            return error(0, "两次输入的密码不一致");
        }
        password = DigestUtils.md5DigestAsHex(password.toString().getBytes()).toLowerCase();
        boolean rs = userService.updatePassword(id, password);
        if (rs) {
            return error(1, "保存成功！");
        } else {
            return error(0, "保存失败！");
        }
    }

    @RequestMapping(path = "/updateStatus", name = "更新用户状态")
    @ResponseBody
    public Result updateStatus(HttpServletRequest req, HttpServletResponse res) {
        String idStr = req.getParameter("id");
        int id = 0;
        if (idStr != null && Validator.isNum(idStr)) {
            id = Integer.parseInt(idStr);
        }
        String status = req.getParameter("status");
        int rs = userService.updateStatus(id, status);
        if (rs > 0) {
            return error(1, "操作成功！");
        } else {
            return error(0, "操作失败！");
        }
    }

    @RequestMapping(path = "/del", name = "删除用户")
    @ResponseBody
    public Result del(HttpServletRequest req, HttpServletResponse res) {
        String idStr = req.getParameter("id");
        int id = 0;
        if (idStr != null && Validator.isNum(idStr)) {
            id = Integer.parseInt(idStr);
        }
        int rs = userService.del(id);
        if (rs > 0) {
            return error(1, "操作成功！");
        } else {
            return error(0, "操作失败！");
        }
    }
}
